<template>
  <el-dialog :title="!dataForm.id? '新增' : '修改'" :close-on-click-modal="false" :visible.sync="visible">
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" label-width="100px">
      <el-form-item label="商品分类" prop="catName">
        <el-popover
          ref="goodsCatsPopover"
          placement="bottom-start"
          trigger="click">
          <el-tree
            :data="goodsCats"
            :props="goodsCatsTreeProps"
            node-key="id"
            ref="goodsCatsTree"
            @current-change="goodsCatsTreeCurrentChangeHandle"
            :default-expand-all="false"
            :highlight-current="true"
            :expand-on-click-node="false">
          </el-tree>
        </el-popover>
        <el-input v-model="dataForm.catName"
          v-popover:goodsCatsPopover
          :readonly="true"
          placeholder="点击选择商品分类"
          class="menu-list__input"
        ></el-input>
      </el-form-item>
      <el-form-item label="商品名称" prop="goodsName">
        <el-input v-model="dataForm.goodsName" placeholder="商品名称" maxlength="50"></el-input>
      </el-form-item>
      <el-form-item label="商品单位" prop="goodsUnit">
        <el-input v-model="dataForm.goodsUnit" placeholder="例如：次、瓶、个、件" maxlength="10"></el-input>
      </el-form-item>
      <el-form-item label="商品单价" prop="goodsPrice">
        <el-input v-model="dataForm.goodsPrice" placeholder="商品单价"></el-input>
      </el-form-item>
      <el-form-item label="折扣率" prop="goodsDiscount">
        <el-input v-model="dataForm.goodsDiscount" placeholder="折扣率1-100" maxlength="3"></el-input>
      </el-form-item>
      <el-form-item label="结账限制" prop="cardTypes">
        <el-checkbox-group v-model="dataForm.cardTypes">
          <el-checkbox label="1">次卡</el-checkbox>
          <el-checkbox label="2">充值卡</el-checkbox>
          <el-checkbox label="3">积分卡</el-checkbox>
          <el-checkbox label="4">散客</el-checkbox>
        </el-checkbox-group>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" :disabled="disabled" @click="dataFormSubmit()">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
  export default {
    props: {
      companyId: {
        type: Number
      },
      goodsCats: {
        type: Array,
        default: function(){
          return []
        }
      }
    },
    data() {
      var checkPrice = (rule, value, callback) => {
        if (!value) {
          return callback(new Error("请填写价格"));
        }
        if (!/^\d+(\.\d{0,2})?$/.test(value)) {
          callback(new Error("请填写正确的价格"));
        } else if (value <= 0) {
          callback(new Error("价格必须大于0"));
        } else {
          callback();
        }
      };
      var checkDiscount = (rule, value, callback) => {
        if (!value) {
          return callback(new Error("请填写折扣率"));
        }
        if (!/^([1-9][0-9]{0,1}|100)$/.test(value)) {
          callback(new Error("请输入1-100之间的整数"));
        } else if (value <= 0) {
          callback(new Error("请输入1-100之间的整数"));
        } else {
          callback();
        }
      };
      return {
        visible: false,
        disabled: false,
        dataForm: {
          id: null,
          catId: null,
          companyId: null,
          goodsName: '',
          goodsUnit: '',
          goodsPrice: null,
          goodsDiscount: null,
          cardType: '',
          cardTypes: ['1','2','3','4'],
          catName: ''
        },
        goodsCatsTreeProps: {
          label: 'catName',
          children: 'children'
        },
        dataRule: {
          catName: [{
            required: true,
            message: '请选择所属分类',
            trigger: 'blur'
          }],
          goodsName: [{
            required: true,
            message: '商品名称不能为空',
            trigger: 'blur'
          }],
          goodsUnit: [{
            required: true,
            message: '商品单位不能为空',
            trigger: 'blur'
          }],
          goodsPrice: [{
            validator: checkPrice,
            trigger: 'blur'
          }],
          goodsDiscount: [{
            validator: checkDiscount,
            trigger: 'blur'
          }],
          cardTypes: [{
            required: true,
            message: '请选择结账限制',
            trigger: 'blur'
          }]
        }
      }
    },
    methods: {
      init(id) {
        this.dataForm = {
          id: id || null,
          catId: null,
          companyId: null,
          goodsName: '',
          goodsUnit: '',
          goodsPrice: null,
          goodsDiscount: null,
          cardType: '',
          cardTypes: ['1','2','3','4'],
          catName: ''
        };
        this.$nextTick(() => {
          if (this.dataForm.id) {
            const loading = this.$loading({
              lock: true,
              text: 'Loading',
              spinner: 'el-icon-loading',
              background: 'rgba(0, 0, 0, 0.7)'
            });
            this.$http({
              url: this.$http.adornUrl(`/merchant/goods/detail/${this.dataForm.id}`),
              method: 'get',
              params: this.$http.adornParams()
            }).then(({
              data
            }) => {
              loading.close()
              if (data && data.code === 0) {
                this.dataForm.catId = data.item.catId;
                this.dataForm.companyId = data.item.companyId;
                this.dataForm.goodsName = data.item.goodsName;
                this.dataForm.goodsUnit = data.item.goodsUnit;
                this.dataForm.goodsPrice = data.item.goodsPrice;
                this.dataForm.goodsDiscount = data.item.goodsDiscount;
                this.dataForm.cardType = data.item.cardType;
                this.dataForm.cardTypes = data.item.cardType.split(',');
                this.visible = true
                this.goodsCatTreeSetCurrentNode()
              }
            }).catch(() => {
              loading.close()
            })
          } else {
            this.visible = true
            this.$nextTick(() => {
              this.goodsCatTreeSetCurrentNode()
            })
          }
        })
      },
      // 表单提交
      dataFormSubmit() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            var cardType = '';
            if(this.dataForm.cardTypes.length === 0){
              this.$message.error("请选择结账限制");
              return false
            }
            this.dataForm.cardTypes.forEach(item => {
              cardType += ',' + item
            });
            cardType = cardType.substring(1,cardType.length)
            this.disabled = true;
            this.$http({
              url: this.$http.adornUrl(`/merchant/goods/${!this.dataForm.id ? 'save' : 'update'}`),
              method: 'post',
              data: this.$http.adornData({
                id: this.dataForm.id || undefined,
                catId: this.dataForm.catId,
                companyId: this.companyId,
                goodsName: this.dataForm.goodsName,
                goodsUnit: this.dataForm.goodsUnit,
                goodsPrice: this.dataForm.goodsPrice,
                goodsDiscount: this.dataForm.goodsDiscount,
                cardType: cardType
              })
            }).then(({
              data
            }) => {
              this.disabled = false;
              if (data && data.code === 0) {
                this.$message({
                  message: '操作成功',
                  type: 'success',
                  duration: 1500,
                  onClose: () => {
                    this.visible = false;
                    this.$emit('refreshDataList');
                  }
                })
              } else {
                this.$message.error(data.msg);
              }
            })
          }
        })
      },
      // 分类树选中
      goodsCatsTreeCurrentChangeHandle(data, node){
        this.dataForm.catId = data.id
        this.dataForm.catName = data.catName
      },
      goodsCatTreeSetCurrentNode(){
        this.$refs.goodsCatsTree.setCurrentKey(this.dataForm.catId)
        this.dataForm.catName = (this.$refs.goodsCatsTree.getCurrentNode() || {})['catName']
      }
    }
  }
</script>
